package com.goddess.yeecolor.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.goddess.yeecolor.Modle.BaoMinInfo;
import com.goddess.yeecolor.Modle.Comment;
import com.goddess.yeecolor.Modle.activity;
import com.goddess.yeecolor.Modle.basic;
import com.goddess.yeecolor.Modle.belong_info;
import com.goddess.yeecolor.Modle.comments;
import com.goddess.yeecolor.Modle.user_info;
import com.goddess.yeecolor.Modle.xRefreshMethed;
import com.goddess.yeecolor.R;
import com.goddess.yeecolor.adapter.EnrollNumberAdapter;
import com.goddess.yeecolor.adapter.ExerciseItemBaoMinAdapter;
import com.goddess.yeecolor.adapter.Item_Exerciseitem_commitAdapter;
import com.goddess.yeecolor.adapter.activityDetailsAdapter;
import com.goddess.yeecolor.adapter.item_Exerciseitem_commit_contentAdapter;
import com.goddess.yeecolor.base.BaseActivity;
import com.goddess.yeecolor.interfaceAll.OnClickListener;
import com.goddess.yeecolor.tools.Constans;
import com.goddess.yeecolor.tools.JumpIntents;
import com.goddess.yeecolor.tools.LogUtils;
import com.goddess.yeecolor.tools.MyUrl;
import com.goddess.yeecolor.tools.OkttpUtils;
import com.goddess.yeecolor.tools.SharePreceUtils;
import com.goddess.yeecolor.tools.ToastUtils;
import com.goddess.yeecolor.view.Item_ExerciseItemButtom;
import com.goddess.yeecolor.view.LoadingDialog;
import com.goddess.yeecolor.view.MyBanner;
import com.goddess.yeecolor.view.PopPopuWindowUtils;
import com.goddess.yeecolor.view.RecycleViewDivider;
import com.goddess.yeecolor.view.dialog_progress;
import com.goddess.yeecolor.view.sharePopuWindow;
import com.youth.banner.Banner;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.ShareSDK;
/**
 * 活动详情
 */
public class ExerciseItemActivity extends BaseActivity implements View.OnClickListener{
    private List<activity>mList;
    private String webview;
    private JSONArray activity,workers;
    private double price;
    private PopPopuWindowUtils popuWindowUtils;
    private int islike,isapply;//判断底部收藏 购买
    private String id,title;
    /**
     * 已报名的人数
     */
    private ExerciseItemBaoMinAdapter baomingAdapter;

    /**
     * 轮播图父类
     */
    private LinearLayout mLinearBanner;
    private TextView exercise_baoming,exerciseitem_commit;//已报名
    private RecyclerView exercise_recyclerview,exerciseitem_commit_content;
    private ImageView exercise_baomingDetaile;//已报名的按钮
    private LinearLayout exercise_liearbaoming;
    private WebView mWebView;
    private List<String>images;
    private Banner banner;
    private Toolbar mToolbar;
    private View mView;
    private TextView mTitle;
    private String type;
    private boolean isLogin=false;
    private RecyclerView fragment_details_recyclerview,fragment_details_recyclerviewlist;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        mView= LayoutInflater.from(this).inflate(R.layout.activity_exerciseitem,null);
        setContentView(mView);
        ShareSDK.initSDK(this);
        Bundle bundle=getIntent().getBundleExtra("bundle");
        id=bundle.getString("id");
        type=bundle.getString("typed");
        title=bundle.getString("title");
        initFindView();
        initData();
    }

    /**
     * 判断是否登录跳转登录界面
     */
    private void JumpLogin(){
        JumpIntents.startIntent(ExerciseItemActivity.this,LoginAcitivity.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isLogin=SharePreceUtils.getBoolean("user","isLogin");
    }

    private dialog_progress dialog_progress;
    private void setProgress(){
        dialog_progress=new dialog_progress(this);
        dialog_progress.requestWindowFeature(Window.FEATURE_NO_TITLE);

        dialog_progress.setCanceledOnTouchOutside(false);//按返回键可以关闭进度条
        dialog_progress.show();
    }

    @Override
    public void initOnClck() {

    }

    @Override
    public void initFindView() {
        mToolbar= (Toolbar)findViewById(R.id.title_toobar);
        mTitle= (TextView) findViewById(R.id.title_content);

        fragment_details_recyclerview= (RecyclerView) findViewById(R.id.fragment_details_recyclerviews);
        manager=new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        fragment_details_recyclerview.setLayoutManager(manager);
        fragment_details_recyclerview.addItemDecoration(new RecycleViewDivider(this, manager.HORIZONTAL, 1, Color.rgb(211, 211, 211)));
        mTitle.setText("活动详情");
        mWebView= (WebView) findViewById(R.id.exercise_webview);
        exercise_baoming= (TextView) findViewById(R.id.exercise_baoming);
        exercise_baomingDetaile= (ImageView) findViewById(R.id.exercise_baomingDetaile);
        exerciseitem_commit= (TextView) findViewById(R.id.exerciseitem_commit);
        exercise_liearbaoming= (LinearLayout) findViewById(R.id.exercise_liearbaoming);
        mToolbar.setTitleTextColor(getResources().getColor(R.color.purple));
//        setSupportActionBar(mToolbar);
//        getSupportActionBar().setDisplayShowTitleEnabled(false);

        // 左上的图标按钮
        mToolbar.setNavigationIcon(R.mipmap.back3x);
        // 左上的图标按钮点击事件
        mToolbar.setNavigationOnClickListener(view -> {
            setFiish(this);
        });


        exercise_baomingDetaile.setOnClickListener(this);
        exerciseitem_commit.setOnClickListener(addCommentListener);


//        /**
//         * 已报名人数
//         */
//        setBaoMin();
//        /**
//         * 底部
//         */
//        setButtom();

    }
    /**
     * webview
     */
    private void setWebview(String webview){
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl(webview);
    }
    /**
     * 获取数据 信息
     */
    private List<activity>mLists;
    private String ln,la,titles;
    private activityDetailsAdapter adapterAcitivity;
    private void getData(JSONArray array){
        mLists=new ArrayList<>();
        try {
            JSONArray jsonArray=array;
            for (int i=0;i<jsonArray.length();i++){
                JSONObject data=jsonArray.getJSONObject(i);
                activity activity=new activity();
                activity.setText(data.optString("text"));
                activity.setType(data.optString("type"));

                if (data.has("image")){
                    activity.setImage(data.optString("image"));
                }
                if (data.has("func")){

                    activity.setFunc(data.optString("func"));
                }
                if (data.has("la")){

                    la=data.optString("la");

                    titles=data.optString("text");
                    activity.setLa(data.optString("la"));
                }
                if (data.has("ln")){
                    ln=data.getString("ln");
                    activity.setLn(data.optString("ln"));
                }
                if (data.has("tel")){

                    activity.setTel(data.optString("tel"));
                }
                mLists.add(activity);
            }
            adapterAcitivity=new activityDetailsAdapter(mLists,this,1);
            fragment_details_recyclerview.setAdapter(adapterAcitivity);

            adapterAcitivity.setOnClickListener(new OnClickListener() {
                @Override
                public void OnClick(View view, int position) {
                    activity activity=mLists.get(position);
                    if (activity.getFunc()!=null){
                        if (activity.getFunc().equals("map")){
                            //地图
                            if (!la.isEmpty()&&ln.isEmpty()){
                                Bundle bundle=new Bundle();
                                bundle.putString("ln",ln);
                                bundle.putString("la",la);
                                bundle.putString("title",titles);
                                JumpIntents.startIntent(ExerciseItemActivity.this,ExerciseMapActivity.class,bundle);

                            }
                        }
                        else if (activity.getFunc().equals("tel")){
                            phone=activity.getTel();
                            if (!phone.isEmpty()){
                                if(hasPermissin(Manifest.permission.CALL_PHONE)){
                                    doCall();
                                }
                                else {
                                    //请求权限
                                    requestPermission(Constans.WRIGTE_CALL_EXTERNAL_CODE,Manifest.permission.CALL_PHONE);
                                }
                            }

                        }
                    }
                }

                @Override
                public void OnLongClick(View view, int position) {

                }
            });
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }


    private Map<Object,Object>map;
    @Override
    public void initData() {
        setProgress();
        map=new HashMap<>();
        map.put("event_id",id);
        map.put("unique", SharePreceUtils.getOther("user","unique"));
        LogUtils.getInstence().info(MyUrl.url+MyUrl.events_detalis+"?event_id="+id+"&unique="+SharePreceUtils.getOther("user","unique"));
        setRequest(MyUrl.url+MyUrl.events_detalis,map,handler,1);
    }
    private void setRequest(String url, Map<Object,Object> map, Handler handler, int tag){
        OkttpUtils.getIntence().OkttpPost(url,map,handler,tag);
    }
    /**
     * 设置轮播图
     */
    private void setBanner(){
        mLinearBanner= (LinearLayout) findViewById(R.id.lineBanner);
        Banner banner= MyBanner.getIntence().init(mView, images, this);
        mLinearBanner.addView(banner);
        banner.setOnBannerClickListener((position)-> {

        });

    }

    /**
     * 设置 活动详情标题等
     */
    private LoadingDialog dialog;
    private String phone;
    @Override
    public  void doCall(){

        LoadingDialog dialog=new LoadingDialog(this,ExerciseItemActivity.this,phone,1);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }
    /**
     * 设置webView;
     */
    public void setWebView(String url){
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.loadUrl(url);
    }

    @Override
    public void onClick(View view) {
        int ids=view.getId();
        switch (ids){
            case R.id.exercise_baomingDetaile://已报名的人数跳转按钮
                Bundle bundle=new Bundle();
//                bundle.putInt("number",count);
                bundle.putString("id",id+"");
                JumpIntents.startIntent(ExerciseItemActivity.this,EnrollNumberAcitivity.class,bundle);
                break;


        }
    }



    /**
     * 已报名人数
     */
    private void setBaoMin(){

        /**
         * 设置recyclerview的布局管理器
         */
        exercise_recyclerview= (RecyclerView) findViewById(R.id.exercise_recyclerview);
        LinearLayoutManager manger=new LinearLayoutManager(this);
        manger.setOrientation(LinearLayoutManager.HORIZONTAL);
        exercise_recyclerview.setLayoutManager(manger);
        map=new HashMap<>();
        map.put("event_id",id);
        setRequest(MyUrl.workers,map,handler,1);




    }

    /**
     * 设置底部分享等
     */
    private sharePopuWindow share;
    private void setButtom(){
        /**
         * 分享
         */
        AppBarLayout linearLayout= (AppBarLayout) findViewById(R.id.appbar);
        share=new sharePopuWindow(this,MyUrl.TYPE,typed+"");
        Item_ExerciseItemButtom.initShare(mView, (view)->{
                    share.showAsDropDown(linearLayout, Gravity.CENTER,0,0);

                }
        );
        /**
         * 收藏
         */
        Item_ExerciseItemButtom.initCollect(mView, new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        },islike);
        Item_ExerciseItemButtom.textCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLogin){
                    if (islike==0){
                        map=new HashMap<Object, Object>();
                        map.put("id",typed+"");
                        map.put("unique", SharePreceUtils.getOther("user","unique"));
                        map.put("typed",MyUrl.TYPE);
                        setRequest(MyUrl.COLLECT,map,handler,2);

                    }
                    else if (islike==1){//取消

                        map=new HashMap<Object, Object>();
                        map.put("id",typed+"");
                        map.put("unique", SharePreceUtils.getOther("user","unique"));
                        map.put("typed",MyUrl.TYPE);
                        setRequest(MyUrl.COLLECT,map,handler,2);

                    }
                }
                else {
                    JumpLogin();
                }

            }
        });



        /**
         * 购买
         * */

        OnClickLintener onClickLintener=new OnClickLintener();
        //弹窗

//        isapply=1;

        popuWindowUtils=new PopPopuWindowUtils(this,onClickLintener,"查看报名凭证","取消报名",isapply);

        Item_ExerciseItemButtom.initBuy(mView,isapply,price);
        Item_ExerciseItemButtom.buyLinear.setOnClickListener((view1)->{
            OnClickLintener paramOnClickListener = new OnClickLintener();
            if (isapply==1){//我已报名
//                popuWindowUtils.showAsDropDown(linearLayout, Gravity.CENTER,0,0);
                /**
                 * 取消报名
                 */
                popuWindowUtils.popuwindow_cancalenroll.setOnClickListener((view)->{
                    map=new HashMap<Object, Object>();
                    map.put("order_id",order_id+"");//购买order_id
                    map.put("unique", SharePreceUtils.getOther("user","unique"));
                    setRequest(MyUrl.CALCALBUY,map,handler,4);
                });
                /**
                 * 查看凭证
                 */
                popuWindowUtils.popuwindow_examine.setOnClickListener((view)->{
                    map=new HashMap<Object, Object>();
                    map.put("state",state+"");//购买order_id
                    map.put("unique", SharePreceUtils.getOther("user","unique"));
                    setRequest(MyUrl.BUYLIST,map,handler,5);
                });
            }
            else if (isapply==0){//购买

                if (isLogin){
                    Bundle bundle=new Bundle();
                    bundle.putString("buy_id",typed+"");
                    bundle.putString("type",MyUrl.TYPE);
                    bundle.putString("order_id",order_id);
                    JumpIntents.startIntent(ExerciseItemActivity.this,ReusingRaymentActivity.class,bundle);//跳转到支付界面
                }
                else {
                    JumpLogin();
                }

            }
            else if (isapply==2){

            }
        });
    }


    /**
     * popuwindow的弹框
     */
    class OnClickLintener implements View.OnClickListener{
        @Override
        public void onClick(View view) {
        }
    }


    /**
     * 活动评论
     */
    private void activityComments(View mView){
//        exerciseitem_commit_content= (RecyclerView) findViewById(R.id.exerciseitem_commit_content);
        setRecyclerview(mView);

    }

    private List<comments> replyList;
    private Button btn_comment, btn_reply;
    private EditText edt_reply;
    private static Activity mactivity;
    private RecyclerView lv_user_comments;
    private static final int ONE_COMMENT_CODE = -1;
    private item_Exerciseitem_commit_contentAdapter commentReplyAdapter;
    private List<Comment> commentList = new ArrayList<Comment>();

    private LinearLayoutManager manager;
    private XRefreshView xRefreshView;
    public static long lastRefreshTime;
    public void setRecyclerview(View view){
        init();


    }

    private LinearLayoutManager mLinearManager;
    private Item_Exerciseitem_commitAdapter commentAdapter;
    private int page=1;
    private void init() {
        xRefreshView= (XRefreshView) findViewById(R.id.exerciseitem_xrefresh);
        lv_user_comments= (RecyclerView) findViewById(R.id.mRecyclerview);
        commentList = new ArrayList<Comment>();
        lv_user_comments.setHasFixedSize(true);
        initCommentData();

        mLinearManager = new LinearLayoutManager(this);
        lv_user_comments.setLayoutManager(mLinearManager);
        lv_user_comments.addItemDecoration(new RecycleViewDivider(this, mLinearManager.HORIZONTAL, 1, Color.rgb(211, 211, 211)));

        setRefrsh();


    }
    private void initCommentData() {
        map=new HashMap<Object, Object>();
        map.put("page",page+"");
        map.put("comment_id",id+"");
        map.put("typed",MyUrl.TYPE);
        LogUtils.getInstence().info(MyUrl.getcommit+"?comment_id="+id+"&page="+page+"&typed="+MyUrl.TYPE);
        setRequest(MyUrl.getcommit,map,handlerCommit,1);

    }
    /**
     * 发表评论的监听
     */
    private int TAG_SEND=1;
    private int TAG_FLOOR=2;
    private int TAG_MUTAL=3;
    public String level="0";
    public String comment_id;
    private View.OnClickListener addCommentListener =(v)-> {
        if (isLogin){

            Bundle bundle=new Bundle();
            bundle.putInt("tag",TAG_SEND);
            bundle.putString("typed",MyUrl.TYPE);
            bundle.putString("level",level);
            bundle.putString("comment_id",id+"");//发表评论获取单行的id
            JumpIntents.startIntentResultIntent(this,CommitActivity.class,1,bundle);
        }
        else {
            JumpLogin();
        }
    };
    /**
     * 回复评论的监听（回复楼主）
     */
    private View.OnClickListener replyToCommentListener = (v)->{
        if (isLogin) {
            int position = (Integer) v.getTag();

            //level 发表评论0   回复是id
            Bundle bundle = new Bundle();
            bundle.putInt("position", position);
            bundle.putInt("tag", TAG_FLOOR);
            bundle.putString("typed", MyUrl.TYPE);
            bundle.putString("level", commentList.get(position).getId() + "");
            bundle.putString("comment_id", comment_id);
            JumpIntents.startIntentResultIntent(this, CommitActivity.class, TAG_FLOOR, bundle);
        }
        else {
            JumpLogin();
        }

    };

    /**
     * 互相回复的监听（楼中楼）
     */
    private View.OnClickListener replyToReplyListener = (v)->{

        if (isLogin){
            int parentPosition = (Integer) v.getTag(R.id.tag_first);
            int childPosition = (Integer) v.getTag(R.id.tag_second);
//        int position = (Integer) v.getTag();
            //level 发表评论0   回复是id
            Bundle bundle=new Bundle();
            bundle.putInt("parentPosition",parentPosition);
            bundle.putInt("childPosition",childPosition);
            bundle.putInt("tag",TAG_MUTAL);
            bundle.putString("typed",MyUrl.TYPE);
            bundle.putString("level",commentList.get(parentPosition).getCommentses().get(childPosition).getId()+"");
            bundle.putString("comment_id",comment_id);
            JumpIntents.startIntentResultIntent(this,CommitActivity.class,TAG_MUTAL,bundle);
        }
        else {
            JumpLogin();
        }

    };


    /**
     * 结果回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

            switch (requestCode){
                case 1:
                    if (resultCode==TAG_SEND){//发送评论
                        setResults(1,data);
                    }
                    break;
                case 2:
                    if (resultCode==TAG_FLOOR){//回复楼主
                        setResults(2,data);
                    }
                    break;
                case 3:
                    if (resultCode==TAG_MUTAL){
                        setResults(3,data);
                    }
                    break;
            }
    }

    private int isid;
    public void setResults(int tag,Intent data){
        page=1;
        commentList.clear();
        if (tag==1){
            TAG_PULL="NORMAR";
            initCommentData();
        }
        else if(tag==2){
            TAG_PULL="NORMAR";

            initCommentData();
        }
        else if (tag==3){
            TAG_PULL="NORMAR";

            initCommentData();
        }

    }

    /**
     * 评论
     * @param parentPositon
     * @param childPostion
     */
    private void sendCommit(final int parentPositon,
                            final int childPostion,String content,String addtime,String name,String thumb,String zan){
        switch (childPostion) {
            case ONE_COMMENT_CODE:

                Comment comment = new Comment();
                comment.setContent(content);
                comment.setTime(addtime);
                comment.setZan(zan);
                user_info info=new user_info();
                basic basic= new basic();
                basic.setNickname(name);
                basic.setThumb(thumb);

                info.setBasic(basic);
                comment.setInfo(info);

                commentList.add(comment);
                /**
                 * 插入数据到顶部
                 */
                commentAdapter.insert(comment,0);
                break;
            default:
                comments comments=new comments();
                comments.setContent(content);
                user_info userInfos=new user_info();
                belong_info infob=new belong_info();

//                if ()
                if (parentPositon != -1) {

//                    comments.setInfo();
//                    reply.setReplyTo(commentList.get(parentPositon)
//                            .getReplyList().get(childPostion)
//                            .getUsername());
//                    commentList.get(parentPositon).getReplyList()
//                            .add(reply);
                } else {//回复楼主
                    basic basicb=new basic();
                    basic basic1=new basic();
                    basic1.setNickname(name);
                    basic1.setContent(content);
                    basic1.setId(isid);
                    basicb.setNickname(name);
                    basicb.setContent(content);
                    basicb.setId(isid);
                    userInfos.setBasic(basic1);
                    infob.setBasic(basicb);
                    comments.setInfo(userInfos);
                    comments.setBelong(infob);
                    replyList=commentList.get(childPostion).getCommentses();

                    replyList.add(comments);

                    commentList.get(childPostion).setCommentses(replyList);
                }
                commentAdapter.clearList();
                commentAdapter.updateList(commentList);
                commentAdapter.notifyDataSetChanged();
                break;

        }

    }
    private int lomode;
    private void setRefrsh() {
        /**
         * 上拉 和下拉
         */
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener(){
//

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);

                TAG_PULL="MODE";
                page++;
                initCommentData();
            }
        });


    }
    @Override
    protected void onStop() {
        super.onStop();
        if (dialog!=null){
            dialog.dismiss();
        }
    }

    private String TAG_PULL="NORMAR";
    /**
     *解析数据
     */
    private int buy_id;
    private String order_id;
    private String jsonString;
    private int code;
    private int typed;//id
    private int state;//状态

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try{
                images=new ArrayList<>();
                jsonString=msg.getData().getString("result");
                JSONObject object=new JSONObject(jsonString);
                code=object.getInt("code");
                if (code==100){
                    JSONObject result=object.getJSONObject("result");
                    if (msg.what==1){
                        typed=result.getInt("id");
                        price=result.getDouble("price");
                        state=result.getInt("state");
                        JSONArray atlas=result.getJSONArray("atlas");
                        images=new ArrayList<>();
                        for (int i=0;i<atlas.length();i++){
                            images.add(atlas.getString(i));
                        }
                        order_id=result.optString("order_id");
                        /**
                         * 轮播图
                         */
                        setBanner();
                        JSONObject operation=result.getJSONObject("operation");
                        LogUtils.getInstence().info(operation+"收藏");
                        islike=operation.getInt("islike");//收藏

                        isapply=operation.getInt("isapply");//购买
                        setButtom();
                        /**
                         * 信息
                         */
                        getData(result.getJSONArray("activity"));//活动须知
                        webview=result.getString("webview");//活动webview

                        setWebview(webview);
                        workers=result.getJSONArray("workers");//已报名人数
                        setWorkers(workers);
                        /**
                         * 活动评论
                         */
                        activityComments(mView);
                    }
                    else if(msg.what==2){

                        if (islike==0){//收藏
                            ToastUtils.setToast(object.getString("msg"),R.mipmap.activebottomlike3x,ExerciseItemActivity.this);
                            Item_ExerciseItemButtom.initCollect(mView,(view1 )-> {

                            },1);
                            islike=1;
                        }
                        else {
                            ToastUtils.setToast(object.getString("msg"),R.mipmap.collect,ExerciseItemActivity.this);
                            Item_ExerciseItemButtom.initCollect(mView,(view1 )-> {

                            },0);
                            islike=0;
                        }
                    }
                    /**
                     * 购买
                     */
                    else if (msg.what==3){
//                        ToastUtils.setToastText(object.getString("extends"),ExerciseItemActivity.this);
//                        JSONObject events=result.getJSONObject("events");
//                        int id=result.getInt("id");
//                        buy_id=result.getInt("buy_id");
//                        String typed=result.getString("typed");
//                        order_id=result.getString("order_id");
//                        SharePreceUtils.saveOrder(order_id,events.getString("title"),result.getString("price"));
//                        Bundle bundle=new Bundle();
//
//                        bundle.putString("order_id",order_id);
//                        bundle.putString("title",events.getString("title"));
//                        bundle.putString("price",result.getString("price"));
//                        bundle.putString("thumb",events.getString("thumb"));
//                        bundle.putString("typed",typed);
//                        JumpIntents.startIntent(ExerciseItemActivity.this,ReusingRaymentActivity.class,bundle);//跳转到支付界面
                    }
                    else if (msg.what==4){}

                }
                else if(code==403){
                    ToastUtils.toast(object.getString("msg"));
                }
                if (dialog_progress.isShowing()){
                    dialog_progress.dismiss();
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    };


    /**
     * 报名人数
     */
    private EnrollNumberAdapter adapter;
    private List<BaoMinInfo>mListBaoMing;
    private void setWorkers(JSONArray array){
        fragment_details_recyclerviewlist= (RecyclerView) findViewById(R.id.exercise_recyclerview);
        manager=new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
        fragment_details_recyclerviewlist.setLayoutManager(manager);
//        fragment_details_recyclerviewlist.addItemDecoration(new RecycleViewDivider(this, manager.VERTICAL, 1, Color.rgb(211, 211, 211)));
        try {
            mListBaoMing=new ArrayList<>();
            JSONArray items=array;

            for (int i=0;i<items.length();i++){
                JSONObject data=items.getJSONObject(i);

                BaoMinInfo item=new BaoMinInfo();
                item.setId(data.getInt("id"));
                item.setUnique(data.getString("unique"));
                item.setThumb(data.getString("thumb"));
                item.setNickname(data.getString("nickname"));
                item.setWeixinid(data.getString("weixinid"));
                item.setIndustry(data.getString("industry"));
                item.setOccupation(data.getString("occupation"));
                item.setCompany(data.getString("company"));
                item.setCity(data.getString("city"));

                mListBaoMing.add(item);

            }

            baomingAdapter = new ExerciseItemBaoMinAdapter(mListBaoMing, ExerciseItemActivity.this);
            fragment_details_recyclerviewlist.setAdapter(baomingAdapter);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 解析评论数据
     */
    private List<user_info>userInfos;
    private List<belong_info>belongInfos;

    /**
     * 解析评论数据
     */
    private Handler handlerCommit=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                jsonString = msg.getData().getString("result");
                JSONObject object = new JSONObject(jsonString);
                code = object.getInt("code");
                if (code==100){
                    if (msg.what==1){
//                        commentList = new ArrayList<Comment>();
                        if (object.has("result")) {
                            JSONArray result = object.getJSONArray("result");
                            for (int i = 0; i < result.length(); i++) {
                                JSONObject data = result.getJSONObject(i);
                                handlerCommitData(data);
                            }
                        }
                        else {
                            JSONObject extend = object.getJSONObject("extends");
                            if (extend.getString("endfull").equals("0")) {
                                ToastUtils.toast("暂无评论");
                                xRefreshView.setLoadComplete(true);
                            }
                        }
                    }
                    else if (msg.what==2){

                        ToastUtils.setToastText(object.getString("msg"),ExerciseItemActivity.this);

                        JSONObject result = object.getJSONObject("result");
                        int iszan=result.getInt("iszan");
//
                        int zan=result.getInt("zan_count");
                        textView.setText(zan+"");

                    }
                }
                else if (code==403){

                    JSONObject extendss=object.getJSONObject("extends");
                    if (extendss.getString("endfull").equals("0")){
                        xRefreshView.setLoadComplete(true);
                        ToastUtils.toast("暂无数据");
                    }
                }
                if (TAG_PULL.equals("MODE")){
                    xRefreshView.stopLoadMore(true);
                }
                else if (TAG_PULL.equals("ZAN")){}
                else {//第一加载数据执行
                    setAdapter();
                }
                if (dialog_progress!=null&&dialog_progress.isShowing()) {

                    dialog_progress.dismiss();
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }

        }
    };
    /**
     * 评论和点赞相同参数地方
     * @param comm
     */
    private List<comments> commentsList;
    private void handlerCommitData(JSONObject comm){
        try{
            JSONObject data=comm;
            Comment comment = new Comment();

            comment.setId(data.getInt("id"));
            comment.setUnique(data.getString("unique"));
            comment.setTime(data.getString("addtime"));
            comment.setContent(data.getString("content"));
            level = data.getString("level");

            comment.setLevel(data.getString("level"));
            comment.setTyepd(data.getString("typed"));
            comment.setReplay(data.getString("replay"));
            comment_id = data.getString("comment_id");
            comment.setComment_id(data.getString("comment_id"));
            comment.setZan(data.getString("zan"));
            String commitNumber = data.getString("comment");

            comment.setComment(commitNumber);
            /**
             * userinfo  楼主
             */

            JSONObject user = data.getJSONObject("user_info");
            JSONObject basicin = user.getJSONObject("basic");
            user_info userInfo = new user_info();
            basic basic = new basic();
            userInfo.setState(user.getInt("state"));
            basic.setId(basicin.getInt("id"));
            basic.setUnique(basicin.getString("unique"));
            basic.setThumb(basicin.getString("thumb"));
            basic.setNickname(basicin.getString("nickname"));
            userInfo.setBasic(basic);
            comment.setInfo(userInfo);
            /**
             *评论分层  判断如果comment 等于0没有分成评论
             */
            if (!data.getJSONArray("comments").isNull(0)) {
                List<comments> commentsList = new ArrayList<>();
                JSONArray array = data.getJSONArray("comments");
                for (int j = 0; j < array.length(); j++) {
                    JSONObject datas = array.getJSONObject(j);
                    comments comments = new comments();
                    comments.setId(datas.getInt("id"));
                    comments.setUnique(datas.getString("unique"));
                    comments.setAddtime(datas.getString("addtime"));
                    comments.setContent(datas.getString("content"));
                    comments.setLevel(datas.getString("level"));
                    comments.setTyepd(datas.getString("typed"));
                    comments.setReplay(datas.getString("replay"));

                    JSONObject userd = datas.getJSONObject("user_info");
                    user_info infos = new user_info();
                    JSONObject basicins = userd.getJSONObject("basic");

                    basic basics = new basic();
                    infos.setState(userd.getInt("state"));
                    basics.setId(basicins.getInt("id"));
                    basics.setNickname(basicins.getString("nickname"));
                    basics.setUnique(basicins.getString("unique"));
                    basics.setThumb(basicins.getString("thumb"));
                    infos.setBasic(basics);
                    comments.setInfo(infos);

                    JSONObject belongs = datas.getJSONObject("belong_info");
                    belong_info belongInfo = new belong_info();
                    JSONObject basicinb = belongs.getJSONObject("basic");
                    basic basicb = new basic();
                    belongInfo.setState(belongs.getInt("state"));
                    basicb.setId(basicinb.getInt("id"));
                    basicb.setNickname(basicinb.getString("nickname"));
                    basicb.setUnique(basicinb.getString("unique"));
                    basicb.setThumb(basicinb.getString("thumb"));
                    belongInfo.setBasic(basicb);
                    comments.setBelong(belongInfo);
                    commentsList.add(comments);
                }
                comment.setCommentses(commentsList);

            }

            if (TAG_PULL.equals("MODE")) {
                commentList.add(comment);
                commentAdapter.insert(comment, commentAdapter.getAdapterItemCount());
            }
            else if (TAG_PULL.equals("ZAN")){
                commentAdapter.removeData(positionzan);
                commentAdapter.addData(positionzan,comment);

            }
            else {
                commentList.add(comment);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 设置适配器
     */
    private void setAdapter(){
        commentReplyAdapter = null;
        commentAdapter = new Item_Exerciseitem_commitAdapter(ExerciseItemActivity.this,ExerciseItemActivity.this, commentList,
                replyToCommentListener, commentReplyAdapter,
                replyToReplyListener,false);
        lv_user_comments.setAdapter(commentAdapter);
        // 静默加载模式不能设置footerview
        lv_user_comments.setAdapter(commentAdapter);
        xRefreshView.setPullRefreshEnable(false);
        xRefreshView.stopLoadMore(true);
        //设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
//        commentAdapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        xRefreshMethed.setRefrsh(xRefreshView);
        commentAdapter.setCustomLoadMoreView(new XRefreshViewFooter(ExerciseItemActivity.this));
        commentAdapter.notifyDataSetChanged();

        commentAdapter.setOnClickListener(new OnClickListener() {
            @Override
            public void OnClick(View view, int position) {
                TAG_PULL="ZAN";
                Comment comment=commentList.get(position);
                positionzan=position;
                textView= (TextView) view.findViewById(R.id.tv_user_praise);
                Map<Object,Object>map=new HashMap<>();
                map.put("id",comment.getId()+"");
                map.put("unique", SharePreceUtils.getOther("user","unique"));
                map.put("typed","comment");
                OkttpUtils.getIntence().OkttpPost(MyUrl.ZAN,map,handlerCommit,2);
            }
            @Override
            public void OnLongClick(View view, int position) {

            }
        });
    }
    private int positionzan;//赞位置
    private TextView textView;//点赞


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ShareSDK.stopSDK(this);
        if (dialog_progress!=null&&dialog_progress.isShowing()){
            dialog_progress.dismiss();
        }
    }


}
